<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="选择账户平台" prop="channelId">
        <el-select v-model="formData.channelId">
          <el-option v-for="item in channelList" :key="item.id" :value="item.id" :label="item.channelName" />
        </el-select>
      </el-form-item>
     
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">前往授权登录</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as AccountApi from '@/api/operate/account'
import {getChannelAuthUrl} from '@/api/operate/channel'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

/**
 * 渠道列表
 */
const props = defineProps(['channelList'])
const channelList =  props.channelList;
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

interface FormData {
  channelId: any
}
const formData = ref<FormData>({
  channelId: undefined,
})
const formRules = reactive({
  channelId: [{ required: true, message: '渠道主键不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AccountApi.getAccount(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗


/**
 * 获取授权链接，跳出到新窗口
 */
const submitForm = async () => {
  let url = await getChannelAuthUrl(formData.value.channelId);
  window.open(url)
}

</script>